package com.upbos.upm.user;

import com.upbos.core.ret.RetCode;
import com.upbos.core.ret.RetData;
import com.upbos.data.core.Pagination;
import com.upbos.sso.SsoManager;
import com.upbos.sso.UserContext;
import com.upbos.sso.entity.SsoUser;
import com.upbos.upm.common.Constants;
import com.upbos.upm.dict.DictUtil;
import com.upbos.upm.entity.DictMapping;
import com.upbos.upm.entity.User;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.upbos.core.ret.RetData.fail;
import static com.upbos.core.ret.RetData.success;

/**
 * <b>Application name：</b> UserController.java <br>
 * <b>Application describing: 用户管理</b> <br>
 * <b>Copyright：</b> Copyright &copy; 2015-2020 yideb.com 版权所有<br>
 * <b>Company：</b> yideb.com <br>
 * <b>Date：</b> 2019年05月11日 17:09 <br>
 * <b>author：</b> <a href="mailto:wangjz@miyzh.com"> Jason </a>
 * <b>version：</b>V4.2.0
 */
@RestController
@RequestMapping("upm/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private SsoManager ssoManager;


    @PostMapping("listUserByOrgId")
    public RetData listUserByOrgId(Integer pageNo, Integer pageSize, String orgId, UserContext userContext) throws Exception {
        if (!userContext.hasPrivilege(Constants.PRIVILEGE_ADMIN_KEY)) {
            orgId = userContext.getSsoUser().getOrgId();
        }

        Pagination userList = userService.listUserByOrgId(pageNo, pageSize, orgId);
        // 翻译用户类型
        DictUtil.translate(userList.getRows(), new DictMapping("userType", "type", "typeName"));
        return success(userList);
    }

    @PostMapping("listUserByDeptId")
    public RetData listUserByDeptId(Integer pageNo, Integer pageSize, String deptId) throws Exception {
        Pagination userList = userService.listUserByDeptId(pageNo, pageSize, deptId);
        // 翻译用户类型
        DictUtil.translate(userList.getRows(), new DictMapping("userType", "type", "typeName"));
        return success(userList);
    }

    @PostMapping("listUserByName")
    public RetData listUserByName(Integer pageNo, Integer pageSize, String orgId, String name, UserContext userContext) throws Exception {
        if (!userContext.hasPrivilege(Constants.PRIVILEGE_ADMIN_KEY)) {
            orgId = userContext.getSsoUser().getOrgId();
        }
        Pagination userList = userService.listUserByName(pageNo, pageSize, orgId, name);
        // 翻译用户类型
        DictUtil.translate(userList.getRows(), new DictMapping("userType", "type", "typeName"));
        return success(userList);
    }
    /**
     * 查询用户拥有的角色
     *
     * @param uid 用户ID
     * @return 用户角色列表
     */
    @PostMapping("listUserRole")
    public RetData listUserRole(String uid) {
        return success(userService.listUserRole(uid));
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @PostMapping("listRole")
    public RetData listRole(UserContext userContext) {
        String orgId = userContext.getSsoUser().getOrgId();
        return success(userService.listRole(orgId));
    }

    /**
     * 保存用户信息以及用户角色
     *
     * @param user  用户信息
     * @param roles 用户角色列表
     * @return 保存成功信息
     * @throws Exception 异常信息
     */
    @PostMapping("saveUser")
    public RetData saveUser(User user, String roles) throws Exception {
        RetData retData = new RetData(RetCode.SUCCESS);
        if (user.getUid() != null) {
            userService.updateUser(user, roles);
            return retData;
        }

        if (userService.existLoginName(user.getLoginName())) {
            retData.setCode(RetCode.FAIL);
            retData.setMsg("登录账号已经存在！");
            return retData;
        }
        return userService.insertUser(user, roles);
    }

    /**
     * 删除用户
     *
     * @param uid 用户ID
     */
    @PostMapping("deleteUser")
    public void deleteUser(String uid) {
        userService.deleteUser(uid);
    }


    /**
     * 修改密码
     *
     * @param request 包装类
     * @return 修改密码结果
     * @throws Exception 异常信息
     */
    @PostMapping("changePassword")
    public RetData changePwd(HttpServletRequest request, String oldPassword, String newPassword) throws Exception {
        SsoUser ssoUser = ssoManager.getSsoUser(request);
        boolean success = userService.modifyPassword(ssoUser.getUid(), oldPassword, newPassword);
        return success ? success() : fail();
    }

    /**
     * 重置密码
     *
     * @param uid      用户ID
     * @param password 重置的新密码
     * @throws Exception 异常信息
     */
    @PostMapping("resetPassword")
    public void resetPassword(String uid, String password) throws Exception {
        userService.resetPassword(uid, password);
    }

    /**
     * 生成用户姓名拼音
     *
     * @param userName 用户姓名
     * @return 用户姓名拼音
     * @throws BadHanyuPinyinOutputFormatCombination 异常信息
     */
    @PostMapping("pinyin")
    public RetData pinyin(String userName) throws BadHanyuPinyinOutputFormatCombination {
        StringBuffer pinyinName = new StringBuffer();
        char[] nameChar = userName.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                pinyinName.append(PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0]);
            } else {
                pinyinName.append(nameChar[i]);
            }
        }

        return success(pinyinName);
    }
}